//
//  HJJsApiTest.m
//  project
//
//  Created by yefei on 2019/8/3.
//  Copyright © 2019 健健. All rights reserved.
//

#import "HJJsApiTest.h"
#import "HJShareView.h"
#import "HJAddBankeVC.h"


@implementation HJJsApiTest

//同步API
- (NSString * _Nonnull)callToken:(NSString *_Nonnull )msg {
    return [HJUserManager getUserModel].token;
}

- (NSString * _Nonnull)callUserId:(NSString *_Nonnull)msg {
    return [HJUserManager getUserModel].userId;
}

-(NSString * _Nonnull)callUser:(NSString * _Nonnull)msg {
    return [[HJUserManager getUserModel] yy_modelToJSONString];
}

- (void)callShare:(NSString *_Nonnull)msg {
    if ([self.delegate respondsToSelector:@selector(shareView)]) {
        [self.delegate shareView];
    }
}

//异步API
- (void)pushToAddBankCardVC:(NSString *_Nonnull)msg completionHandler:(JSCallback _Nullable)completionHandler {
    HJAddBankeVC * bankVC = [HJAddBankeVC new];
//    @weakify(self)
    bankVC.isAdd = YES;
    bankVC.jsApiTestBlock = ^(BOOL isAdd) {
//        @strongify(self)
        completionHandler(isAdd == YES ? @"true":@"false",isAdd);
    };
    [[UIViewController currentViewController].navigationController pushViewController:bankVC animated:YES];
}


- (void)request:(NSDictionary *_Nonnull)msg completionHandler:(JSCallback _Nullable)completionHandler {
    LKLog(@"%@",msg);
    NSString * lowerType = [[NSString stringWithFormat:@"%@",msg[@"type"]] lowercaseString];
    if (lowerType.length && [lowerType isEqualToString:@"get"]) {
        [self getWithUrl:msg[@"url"] param:msg[@"data"] timeout:[msg[@"timeout"] intValue] header:msg[@"heads"] contentType:msg[@"contentType"] completionHandler:^(NSDictionary * _Nullable responseObject, BOOL isSuccess) {
            NSError *parseError = nil;
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:&parseError];
            completionHandler([[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding],YES);
        } errorHandler:^(NSError * _Nullable error) {
            completionHandler(error.localizedDescription,NO);
        }];
        return;
    }
    [self postWithUrl:msg[@"url"] param:msg[@"data"] timeout:[msg[@"timeout"] intValue] header:msg[@"heads"] contentType:msg[@"contentType"] completionHandler:^(NSDictionary * _Nullable responseObject, BOOL isSuccess) {
        NSError *parseError = nil;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:&parseError];
        completionHandler([[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding],YES);
    } errorHandler:^(NSError * _Nullable error) {
        completionHandler(error.localizedDescription,NO);
    }];
}

- (void)postWithUrl:(NSString *_Nonnull)url param:(NSDictionary *_Nonnull)param timeout:(NSInteger)timeout header:(NSDictionary *)header contentType:(NSString *)contentType completionHandler:(successBlock _Nonnull )completionHandler errorHandler:(failureBlock _Nullable)errorHandler {
    
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.requestSerializer.timeoutInterval = timeout;
    mgr.requestSerializer = [AFHTTPRequestSerializer serializer];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [mgr.requestSerializer setValue:@"no-cache" forHTTPHeaderField:@"Cache-Control"];
    for (NSString * key in header.allKeys) {
        NSString * value = [header objectForKey:key];
        [mgr.requestSerializer setValue:[NSString stringWithFormat:@"%@",value] forHTTPHeaderField:key];
    }
    [mgr.requestSerializer setValue:[HJHttpTool token] forHTTPHeaderField:@"Authorization"];
    
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:contentType, nil];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    [mgr POST:url parameters:[HJHttpTool getNewParamsFromParams:param] progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        //判断接口是否成功返回
        NSError * parseError1 = nil;
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&parseError1];
        completionHandler(dic,YES);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSHTTPURLResponse * resp = (NSHTTPURLResponse *)task.response;
        if (resp.statusCode == 401) {
            static dispatch_once_t onceToken;
            dispatch_once(&onceToken, ^{
                @weakify(self)
                [HJHttpTool refreshTokenWithSuccess:^(BOOL isYes) {
                    @strongify(self)
                    if (isYes) {
                        [self postWithUrl:url param:param timeout:timeout header:header contentType:contentType completionHandler:completionHandler errorHandler:errorHandler];
                    }else {
                        [mgr.tasks makeObjectsPerformSelector:@selector(cancel)];
                    }
                }];
            });
            return;
        }else {
            errorHandler(error);
        }
    }];
    
//    //创建配置信息
//    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
//    //设置请求超时时间
//    configuration.timeoutIntervalForRequest = timeout == 0 ? 20 : timeout;
//    //创建会话
//    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
//    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
//    //设置请求方式
//    [request setHTTPMethod:@"POST"];
//
//    [request setValue:contentType forHTTPHeaderField:@"content-Type"];
//    [request setValue:@"no-cache" forHTTPHeaderField:@"Cache-Control"];
//
//    for (NSString * key in header.allKeys) {
//        NSString * value = [header objectForKey:key];
//        [request setValue:[NSString stringWithFormat:@"%@",value] forHTTPHeaderField:key];
//    }
//    [request setValue:[HJHttpTool token] forHTTPHeaderField:@"Authorization"];
//    //设置请求体
//    NSMutableString *bodyMutableStr = [NSMutableString new];
//    NSEnumerator *keyEnum = [[HJHttpTool getNewParamsFromParams:param] keyEnumerator];
//    id key;
//    while (key = [keyEnum nextObject]) {
//        [bodyMutableStr appendString:[NSString stringWithFormat:@"%@=%@&", key, [[HJHttpTool getNewParamsFromParams:param] valueForKey:key]]];
//    }
//    LKLog(@"%@",bodyMutableStr);
//    [request setHTTPBody:[bodyMutableStr dataUsingEncoding:NSUTF8StringEncoding]];
//
//    NSURLSessionDataTask * dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//
//        if (error == nil) {
//
//        }else{
//
//        }
//    }];
//    [dataTask resume];
}

- (void)getWithUrl:(NSString *_Nonnull)url param:(NSDictionary *_Nonnull)param timeout:(NSInteger)timeout header:(NSDictionary *)header contentType:(NSString *)contentType completionHandler:(successBlock _Nullable)completionHandler errorHandler:(failureBlock _Nullable)errorHandler {
    
    NSMutableString *mutableUrl = [[NSMutableString alloc] initWithString:url];
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    configuration.timeoutIntervalForRequest = timeout == 0 ? 20 : timeout;
    
    if ([[HJHttpTool getNewParamsFromParams:param] allKeys]) {
        [mutableUrl appendString:@"?"];
        for (id key in param) {
            NSString *value = [[NSString stringWithFormat:@"%@",[param objectForKey:key]] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
            [mutableUrl appendString:[NSString stringWithFormat:@"%@=%@&", key, value]];
        }
    }
    NSString *urlEnCode = [[mutableUrl substringToIndex:mutableUrl.length - 1] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    LKLog(@"urlEnCode=%@",urlEnCode);
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlEnCode]];
    NSURLSession *urlSession = [NSURLSession sharedSession];
    [urlRequest setValue:[HJHttpTool token] forHTTPHeaderField:@"Authorization"];
    
    NSURLSessionDataTask * dataTask = [urlSession dataTaskWithRequest:urlRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSHTTPURLResponse * resp = (NSHTTPURLResponse *)response;
        if (resp.statusCode == 401) {
            static dispatch_once_t onceToken;
            dispatch_once(&onceToken, ^{
                @weakify(self)
                [HJHttpTool refreshTokenWithSuccess:^(BOOL isYes) {
                    @strongify(self)
                    if (isYes) {
                        [self getWithUrl:url param:param timeout:timeout header:header contentType:contentType completionHandler:completionHandler errorHandler:errorHandler];
                    }else {
                        [dataTask cancel];
                    }
                }];
            });
            return;
        }
        if (error) {
            errorHandler(error);
        } else {
            NSDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            LKLog(@"%@",responseObject);
            completionHandler(responseObject,YES);
        }
    }];
    [dataTask resume];
}



@end
